import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { SelfValidators } from '../../utils/self.validators';
import { UserInfo } from '../domain/User';
import { StorageUtil } from '../../utils/storage.util';
import { PersonalCenterService } from './personal-center.service';
import { StatusEnum } from '../../core/enum/status.enum';
import { HTTP_BASE_URL, SERVERS_NAME } from '../../config/config';
import { Observable, Observer } from 'rxjs';
import { NzMessageService } from 'ng-zorro-antd';
import { debounceTime, distinctUntilChanged, first, map, switchMap } from 'rxjs/operators';
import { Router } from '@angular/router';

@Component({
  selector: 'app-personal-center',
  templateUrl: './personal-center.component.html',
  styleUrls: ['./personal-center.component.scss'],
  providers: [PersonalCenterService]
})
export class PersonalCenterComponent implements OnInit {

  isPwd = false;
  validateForm: FormGroup;
  user: UserInfo = new UserInfo();
  userEdit: UserEdit = new UserEdit();
  nodes = [];
  positionList = [];
  titleList = [];
  // 表格上的过滤
  filterSexArr = [
    {
      text: '男',
      value: 0
    },
    {
      text: '女',
      value: 1
    }
  ];
  avatarUrl: string;
  // 图片上传
  headerInfo = null;
  uploadUrl = `${SERVERS_NAME.UPLOAD_URL}`;
  userPhoto = 'assets/user/photo0.png';
  // 密码开始
  validatePass: FormGroup;
  pwdObj: PwdObj = new PwdObj();

  constructor(private fb: FormBuilder,
              private http: PersonalCenterService,
              private message: NzMessageService,
              private router: Router) {
  }

  ngOnInit() {
    if (StorageUtil.getLocalStorage('user')) {
      this.user = StorageUtil.getLocalStorage('user');
      this.getUser();
    }
    this.initForm();
    this.initPass();
    this.departList();
    this.searchPosition();
    this.searchTitle();
    this.headerInfo = StorageUtil.getFileHeader();
    this.pwdObj.userId = this.user.id;
  }

  /**
   * 查询用户
   */
  getUser() {
    this.http.view(this.user.teacher.id).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.userEdit = res.datas;
        if (res.datas.photo) {
          this.avatarUrl = `${HTTP_BASE_URL}${SERVERS_NAME.SECURITY_SERVER}`
            + 'source/view/' + res.datas.photoSource.moduleName + '/' + res.datas.photoSource.fileNewName;
        } else {
          this.avatarUrl = null;
          this.changePhoto(res.datas.sex);
        }
      }
    });
  }

  /**
   * 基本信息group
   */
  initForm() {
    this.validateForm = this.fb.group({
      id: [null, []],
      name: [this.userEdit.name, [Validators.required]],
      number: [this.userEdit.number, []],
      orgId: [this.userEdit.orgId, [Validators.required]],
      position: [this.userEdit.position, [Validators.required]],
      title: [this.userEdit.title, [Validators.required]],
      telphone: [this.userEdit.telphone, []],
      sex: [this.userEdit.sex, [Validators.required]],
      photo: [this.userEdit.photo, []],
      email: [this.userEdit.email, [SelfValidators.emailValidator]]
    });
  }

  /**
   * 点击基本信息
   * @param bol:false-true
   */
  clickTitle(bol) {
    this.isPwd = bol;
    // 基本信息
    if (!bol) {
      this.initForm();
    } else {
      this.initPass();
    }
  }

  /**
   * 查询部门
   */
  departList() {
    this.http.getDepartment().subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.nodes = res.datas;
      }
    });
  }

  /**
   * 查询职务
   */
  searchPosition() {
    this.http.positionList('teacher-position').subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.positionList = res.datas;
      }
    });
  }

  /**
   * 查询职称
   */
  searchTitle() {
    this.http.positionList('teacher-title').subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.titleList = res.datas;
      }
    });
  }

  beforeUpload = (file: File) => {
    return new Observable((observer: Observer<boolean>) => {
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        this.message.warning('图片大小不能超过5M!');
        observer.complete();
        return;
      }
      observer.next(isLt5M);
      observer.complete();
    });
  }

  private getBase64(img: File, callback: (img: string) => void): void {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result.toString()));
    reader.readAsDataURL(img);
  }

  /**
   * 上传头像
   */
  handleChange(info): void {
    const {file, type} = info;
    if (type === 'success') {
      const {datas, status} = file.response;
      if (status === StatusEnum.SUCCESS) {
        this.getBase64(file.originFileObj, (img: string) => {
          this.avatarUrl = img;
        });
        this.message.success('头像上传成功！');
        this.userEdit.photo = datas.id;
      } else {
        this.message.warning(file.response);
      }
    }
  }

  /**
   * 男女改变
   */
  changePhoto(event) {
    if (event === 1 || event === '1') {
      this.userPhoto = 'assets/user/photo1.png';
    }
    if (event === 0 || event === '0') {
      this.userPhoto = 'assets/user/photo0.png';
    }
  }

  /**
   * 更新用户
   */
  updateUser() {
    this.http.update(this.userEdit).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.message.success(res.message);
      }
    });
  }


  /**
   * 个人密码group
   */
  initPass() {
    this.validatePass = this.fb.group({
      userId: [this.pwdObj.userId, []],
      oldPass: [null, [Validators.required], this.oldPassValidator()],
      newPass: [null, [Validators.required, SelfValidators.letterNumberPwd]],
      resPass: [null, [Validators.required, this.confirmationValidator]],
    });
  }

  /**
   * 验证确认密码
   */
  confirmationValidator = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return {required: true};
    } else if (control.value !== this.validatePass.controls.newPass.value) {
      return {confirm: true, error: true};
    }
    return {};
  }

  /**
   * 旧密码异步校验器
   */
  oldPassValidator() {
    return (control: FormControl): any => {
      return control.valueChanges.pipe(
        distinctUntilChanged(),
        debounceTime(400),
        switchMap(() => this.http.checkPass(this.validatePass.value)),
        map(res => res.status === StatusEnum.SUCCESS && res.datas ? null : {duplicate: true}),
        first()
      );
    };
  }

  /**
   * 修改密码确定
   */
  updatePwd() {
    this.http.updatePass(this.validatePass.value).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        // 密码更改成功，直接跳转到登录页面
        this.message.success(res.message);
        this.router.navigateByUrl('login');
      }
    });
  }

}

class UserEdit {
  email?: string;
  id?: string;
  name?: string;
  number?: string;
  orgId?: string;
  photo?: string;
  photoSource?: any;
  position?: string;
  workType?: string;
  sex = 0;
  telphone?: string;
  title?: string;
  type = 0;
}

class PwdObj {
  newPass?: string;
  oldPass?: string;
  resPass?: string;
  userId?: string;
}
